import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import {UserService} from '../services/user.service';
import {ToastComponent} from '../shared/toast/toast.component';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

  registerForm: FormGroup;
  username = new FormControl('', [
    Validators.required,
    Validators.minLength(5),
    Validators.maxLength(20),
    Validators.pattern('[a-zA-Z0-9_-\\s]*')
  ]);
  password = new FormControl('', [
    Validators.required,
    Validators.minLength(8),
    Validators.maxLength(20)
  ]);
  /*email = new FormControl('', [
    Validators.required,
    Validators.pattern('[\\w]+?@[\\w]+?\\.[a-z]+?')
  ]);
  realName = new FormControl('', [
    Validators.required,
    Validators.minLength(2),
    Validators.maxLength(10),
    Validators.pattern(/^[\u4e00-\u9fa5]*$|^[a-zA-Z ]*$/)
  ]);
  mobile = new FormControl('', [
    Validators.required,
    Validators.pattern(/^(1(([358][0-9]|7[2-9])|(47)))\d{8}$/)
  ]);
  verifyCode = new FormControl('', [
    Validators.required
  ]);*/

  usernameInputFocus = false;
  passwordInputFocus = false;

  setUsernameInputFocus() {
    this.usernameInputFocus = true;
  }

  setUsernameInputBlur() {
    this.usernameInputFocus = false;
  }

  setPasswordInputFocus() {
    this.passwordInputFocus = true;
  }

  setPasswordInputBlur() {
    this.passwordInputFocus = false;
  }

  constructor(private formBuilder: FormBuilder,
              public toast: ToastComponent,
              private router: Router,
              private userService: UserService) {
  }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      username: this.username,
      password: this.password,
      /*email: this.email,
      realName: this.realName,
      mobile: this.mobile,
      verifyCode: this.verifyCode*/
    });
  }

  setClassUsername() {
    return !this.username.pristine && !this.username.valid;
  }

  setClassPassword() {
    return !this.password.pristine && !this.password.valid;
  }

  /*setClassEmail() {
    return {'has-danger': !this.email.pristine && !this.email.valid};
  }

  setClassRealName() {
    return {'has-danger': !this.realName.pristine && !this.realName.valid};
  }

  setClassMobile() {
    return {'has-danger': !this.mobile.pristine && !this.mobile.valid};
  }

  setClassVerifyCode() {
    return {'has-danger': !this.verifyCode.pristine && !this.verifyCode.valid};
  }*/

  register() {
    this.userService.register(this.registerForm.value).subscribe(
      res => this.router.navigate(['/']),
      error => this.toast.setMessage('invalid email or password!', 'danger')
    );
  }
}
